<template>
    <div class='approval'>
        <el-card class="box-card">
            <div class='title'>
                {{$t('approvalDispatch.title1')}}
            </div>
            <div class='menu-search'> 
                <div class='menu-title'>
                  <!-- 进入时间 -->
                  <div class='searchItem searchItem-date'>
                    <span>{{$t('electricOrder.col1')}}</span>
                    <el-date-picker
                    size='small'
                    v-model="listQuery.startDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :placeholder="$t('rule.beginDate')">
                    </el-date-picker>
                    <b>{{$t('approval.go')}}</b>
                    <el-date-picker
                    size='small'
                      v-model="listQuery.endDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      :placeholder="$t('rule.endDate')">
                    </el-date-picker>
                  </div>
                  <!-- 业务渠道 -->
                  <div class='searchItem'>
                    <span>{{$t('customerService.channel')}}</span>
                    <el-select v-model='listQuery.channel' size='small'
                      @change="handleChannelChange">
                      <el-option
                      v-for='item in channelList'
                      :key='item.channel'
                      :label='item.org_name'
                      :value='item.channel'>
                      </el-option>
                    </el-select>
                  </div>  
                  <!-- 用户状态 -->
                  <div class="searchItem">
                    <span>{{$t('electricRecord.UserStatus')}}</span>
                      <el-select v-model="listQuery.saleStatus" size="small">
                        <el-option
                        v-for='(item, index) in userStatusArr'
                        :key='index'
                        :label='item.dictValue'
                        :value='item.dictCode'>
                        </el-option>
                      </el-select>
                  </div>
                  <!-- 手机号 -->
                  <div class="searchItem">
                    <span>{{$t('approval.phoneNo')}}</span>
                    <el-input v-model="listQuery.userPhone" :placeholder="$t('rule.phoneNo')" size="small"></el-input>
                  </div>
                </div>
                <div class='menu-title-btn'>
                  <button type='button' @click='search'>
                      {{$t('btn.query')}}
                  </button>
                  <button type='button' @click='reset'>
                      {{$t('btn.reset')}}
                  </button>
                  <button type='button' @click='importHistoryData'>{{$t('electricOrder.importHis')}}</button>
              </div>
            </div>
        </el-card>
        <el-card class='box-card' style="margin-top: 10px;margin-bottom: 20px;">
            <div class='title'>{{$t('electricOrder.unDisList')}}</div>
            <div class='menu-list'>
              <div>
                <el-button type="text" @click="assignedTo">{{$t('approvalDispatch.assignTo')}}</el-button>
              </div>
            </div>
            <el-table
                v-loading="listLoading"
                ref='multipleTable'
                :data='tableData'
                tooltip-effect='dark'
                style='width: 100%'
                @selection-change='handleSelectionChange'
                border
                size='mini'>
                <el-table-column
                header-align='center'
                align='center'
                type='selection'
                width='55'>
                </el-table-column>
                <!-- 进入时间 -->
                <el-table-column
                prop='innerTime' align="center" header-align="center" 
                :label="$t('electricOrder.col1')"
                width='160'>
                </el-table-column>
                <!-- 客户姓名 -->
                <el-table-column
                prop='userRealName' align="center" header-align="center" 
                :label="$t('electricOrder.col2')"
                width='180'>
                </el-table-column>
                <!-- 手机号 -->
                <el-table-column
                prop='userPhone' align="center" header-align="center" 
                :label="$t('electricOrder.col3')"
                width='180'>
                </el-table-column>
                <!-- 上一笔结清业务ID -->
                <el-table-column
                prop='lastFiveOrderId' align="center" header-align="center" 
                :label="$t('electricOrder.col4')"
                width='140'>
                </el-table-column>
                <!-- 结清本金(RP) -->
                <el-table-column
                prop='lentAmt' align="center" header-align="center" 
                :label="$t('electricOrder.col5')"
                :formatter="cashFormatter"
                width='100'>
                </el-table-column>
                <!-- 借款期限 -->
                <el-table-column
                prop="pTerm" align="center" header-align="center" 
                :label="$t('electricOrder.col6')"
                width='200'>
                </el-table-column>
                <!-- 业务渠道 -->
                <el-table-column
                prop='channelName' align="center" header-align="center" 
                :label="$t('electricOrder.col7')"
                width='200'>
                </el-table-column>
                <!-- 借款APP -->
                <el-table-column
                prop='appPackageName' align="center" header-align="center" 
                :label="$t('electricOrder.col8')"
                width='200'>
                </el-table-column>
                <!-- 用户状态 -->
                <el-table-column
                prop='saleStatusValue' align="center" header-align="center" 
                :label="$t('electricOrder.col9')"
                width='200'>
                </el-table-column>
                <!-- 备注 -->
                <el-table-column
                prop='note' align="center" header-align="center" 
                :label="$t('electricOrder.col25')"
                width='200'>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="listQuery.page"
              :page-sizes="[5, 10, 20, 30]"
              :page-size="listQuery.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
              </el-pagination>
            </div>
        </el-card>
        <el-dialog :title="$t('electricOrder.dispatchLbl')" :visible.sync="dialogFormVisible" :before-close="handlebeforeClose">
          <div class='handler'>
              <span>{{$t('electricOrder.receivePerson')}}</span>
              <el-select v-model='serviceId' :placeholder="$t('rule.choose')" size='small'>
                  <el-option
                  v-for='(item, index) in serviceIds'
                  :key='index'
                  :label='item.value'
                  :value='item.label'>
                  </el-option>
              </el-select>
          </div>
          <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">{{$t('btn.cancel')}}</el-button>
              <el-button type="primary" @click="confirmFn">{{$t('btn.confirm')}}</el-button>
          </div>
        </el-dialog>
        <!--导入历史数据-->
        <el-dialog :title="$t('electricOrder.importHis')"  :visible.sync="dialogFormVisible2" width="30%" center>
          <el-form :model="form" ref="form" :rules="rule" label-width="100px" style="width: 90%;">
            <!-- 导入类型 -->
            <el-form-item :label="$t('electricOrder.importType')" prop="types" >
              <el-select 
              style="width: 100%"
              v-model='form.types' 
              :placeholder="$t('rule.choose')" 
              size='small'
              @change="typeFn(form.types)">
                <el-option
                v-for='(item, index) in typeArr'
                :key='index'
                :label='item.label'
                :value='item.value'>
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 内部数据导入 -->
            <div v-if="isShowTime">
              <!-- 开始时间 -->
              <el-form-item :label="$t('electricOrder.startDate')" prop="startDate">
                <el-date-picker
                  style="width: 100%"
                  size='small'
                  v-model="form.startDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  :placeholder="$t('rule.beginDate')">
                </el-date-picker>
              </el-form-item>
              <!-- 结束时间 -->
              <el-form-item :label="$t('electricOrder.endDate')"  prop="endDate">
                <el-date-picker
                  style="width: 100%"
                  size='small'
                  v-model="form.endDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  :placeholder="$t('rule.endDate')">
                </el-date-picker>
              </el-form-item>
              <!-- 用户状态 -->
              <el-form-item :label="$t('electricOrder.userStatus')" prop="innerType" >
                <el-select 
                style="width: 100%"
                v-model='form.innerType' 
                :placeholder="$t('rule.choose')" 
                size='small'>
                  <el-option
                  v-for='(item, index) in insideStatus'
                  :key='index'
                  :label='item.dictValue'
                  :value='item.dictCode'>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- 外部数据导入 -->
            <div v-if="!isShowTime">
              <!-- 业务渠道 -->
              <el-form-item :label="$t('customerService.channel')" prop="channel" >
                <el-select v-model='form.channel' size='small' style="width: 100%">
                  <el-option
                  v-for='item in channelList'
                  :key='item.channel'
                  :label='item.org_name'
                  :value='item.channel'>
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- 用户状态 -->
              <el-form-item :label="$t('electricOrder.userStatus')" prop="innerType" >
                <el-select 
                style="width: 100%"
                v-model='form.innerType' 
                :placeholder="$t('rule.choose')" 
                size='small'>
                  <el-option
                  v-for='(item, index) in outsideStatus'
                  :key='index'
                  :label='item.dictValue'
                  :value='item.dictCode'>
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- 备注 -->
              <el-form-item :label="$t('user.remarks')" prop="description">
                <el-input
                  size='small'
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 5}"
                  v-model="form.description"
                  :placeholder="$t('electricOrder.descLen')" 
                  :maxlength="100"
                ></el-input>
              </el-form-item>
              <!-- 上传文件 -->
              <el-form-item :label="$t('realTimeData.uploadFile')" ref='file' prop="file">
                <el-checkbox-group v-model="form.file">
                </el-checkbox-group>
                <el-button 
                v-loading.fullscreen.lock="fullscreenLoading"
                :element-loading-text="$t('realTimeData.loading')" 
                element-loading-spinner="el-icon-loading" 
                element-loading-background="rgba(0, 0, 0, 0.8)"
                type="primary" 
                @click.stop="uploadFiles">{{$t('AppUpgrade.subUpload')}}</el-button>
                <form action="" id="videoForm">
                  <input ref="referenceUpload" type="file" value="点击上传文件" @change='onUpload' name="file" class="hiddenInput">
                </form>
              </el-form-item>
            </div>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible2 = false">{{$t('btn.cancel')}}</el-button>
              <el-button v-if="isShowTime" type="primary" @click="confirmImport">{{$t('btn.confirm')}}</el-button>
              <el-button v-if="!isShowTime" type="primary" @click="confirmOutImport">{{$t('btn.confirm')}}</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { formatCash } from '@/utils/index'
import { getChannels, getUnallocatedPage, getGroupMember, assignHandler, importData, getUserStatus, outsideImport } from '@/api/dianxiao/index'
export default {
  name: 'UnDistributedOrder',
  data() {
    return {
      fullscreenLoading: false,
      isShowTime: true,
      listLoading: false,
      total: null,
      listQuery: {
        limit: 5,
        page: 1,
        // 开始时间
        startDate: '',
        // 结束时间
        endDate: '',
        // 渠道
        channel: '',
        // 用户状态
        saleStatus: '',
        // 手机号
        userPhone: ''
      },
      channelList: [],
      tableData: [],
      insideStatus: [],
      outsideStatus: [],
      multipleSelection: [],
      dialogFormVisible: false,
      dialogFormVisible2: false,
      // 客服⼈列表
      serviceIds: [],
      // 客服员id
      serviceId: '',
      form: {
        types: '1',
        startDate: '',
        endDate: '',
        innerType: '',
        description: '',
        file: '',
        channel: ''
      },
      rule: {
        types:  [{
          required: true, message: this.$t('electricOrder.ruleImportType')
        }],
        startDate: [{
          required: true, message: this.$t('electricOrder.required1')
        }],
        endDate: [{
          required: true, message: this.$t('electricOrder.required2')
        }],
        innerType: [{
          required: true, message: this.$t('electricOrder.required3')
        }],
        file: [{
          required: true, message: this.$t('realTimeData.ruleUploadFiles')
        }],
        channel: [{
          required: true, message: this.$t('AppUpgrade.rule5')
        }]
      },
      userStatusArr: [
        {
          dictCode: "",
          dictValue: this.$t("rule.all")
        }
      ],
      typeArr: [
        {
          value: '1',
          label: this.$t('electricOrder.insideType')
        },
        {
          value: '2',
          label: this.$t('electricOrder.outsideType')
        }
      ]
    };
  },
  computed: {
    ...mapGetters(['elements'])
  },
  created() {
    // this.initDate()
    getChannels().then(res => {
      if (res.status === 200 && res.data && res.data.length > 0) {
        this.channelList = this.channelList.concat(res.data)
        this.listQuery.channel = this.channelList[0].channel
        if (this.channelList[0].channel) {
          this.handleChannelChange(this.channelList[0].channel)
        }
        this.getList()
      }
    })
    // 用户状态
    getUserStatus().then(res => {
      if (res.status === 200) {
        this.userStatusArr = this.userStatusArr.concat(res.data) // 列表用户状态下拉
        this.insideStatus = []
        this.outsideStatus = []
        res.data.forEach(item => {
          if (item.attr1 === 'INTERIOR_IMPORT') {
            // 内部数据
            this.insideStatus.push(item)
          } else if (item.attr1 === 'EXTERNAL_IMPORT') {
            // 外部数据
            this.outsideStatus.push(item)
          }
        })
      }
    })
  },
  methods: {
    // 点击上传文件
    uploadFiles() {
      this.$el.querySelector('.hiddenInput').click()
    },
    // 上传成功后的回调
    onUpload(e){
      let $target = e.target || e.srcElement
      let filename = $target.value
      let suffix = filename.substring(filename.lastIndexOf('.') + 1)
      if (suffix === 'xlsx' || suffix === 'xls') {
        let files = $target.files[0]
        if ( files === undefined || files === null || files === '') {
          return
        }
        this.form.file = files
      } else {
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t('electricOrder.fileFormat')
        })
        document.getElementById('videoForm') && document.getElementById('videoForm').reset()
      }
      this.$refs.referenceUpload.value = null
    },
    // 选择下载方式
    typeFn(val) {
      this.form = {
        types: val,
        startDate: '',
        endDate: '',
        innerType: '',
        description: '',
        file: '',
        channel: ''
      }
      this.$refs.form.resetFields()
      if (val === '1') {
        this.isShowTime = true
      } else if (val === '2') {
        this.isShowTime = false
      }
    },
    cashFormatter(row, col, cellValue) {
      return formatCash(cellValue)
    },
    handleChannelChange(val) {
      if (val !== '') {
        getGroupMember(val).then(res => {
          this.serviceId = ''
          if (res.status === 200) {
            this.serviceIds = res.data
          }
        })
      }
    },
    getChannelName(key) {
      if (key) {
        let channelName = ''
        for (let i = 0; i < this.channelList.length; i++) {
          const item = this.channelList[i]
          if (item.channel === key) {
            channelName = item.org_name
            break
          }
        }
        return channelName
      }
    },
    getHandlerName(key) {
      if (key !== '') {
        let designatedName = ''
        for (let i = 0; i < this.serviceIds.length; i++) {
          const item = this.serviceIds[i]
          if (item.label === key) {
            designatedName = item.value
            break
          }
        }
        return designatedName
      }
    },
    getList() {
      this.listLoading = true;
      getUnallocatedPage(this.listQuery).then(res => {
        this.listLoading = false
        if (res.status === 200) {
          const list = res.data.records
          list.forEach(item => {
            item.channelName = this.getChannelName(item.channel)
          })
          this.tableData = res.data.records
          this.total = parseInt(res.data.total)
        }
      })
    },
    // 查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    //重置
    reset() {
      this.listQuery.limit = 5
      this.listQuery.page = 1
      this.listQuery.startDate = ''
      this.listQuery.endDate = ''
      this.listQuery.channel = this.channelList[0].channel
      this.listQuery.saleStatus = ''
      this.listQuery.userPhone = ''
    },
    // 导入历史数据
    importHistoryData() {
      this.form.types = '1'
      this.isShowTime = true
      this.$nextTick(()=>{
        if (this.$refs.form !== undefined) {
          this.$refs.form.resetFields() // 等弹窗里的form表单的dom渲染完在执行this.$refs.form.resetFields()，去除验证
        }
      });
      this.dialogFormVisible2 = true
    },
    // 内部数据导入
    confirmImport() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$confirm(this.$t('approvalDetail.cue1'), {
            confirmButtonText: this.$t('btn.confirm'),
            cancelButtonText: this.$t('btn.cancel'),
            type: "warning",
            center: true
          })
          .then(() => {
            importData(this.form).then(res => {
              if (res.status === 200) {
                this.dialogFormVisible2 = false;
                this.getList();
                this.$message({
                  showClose: true,
                  message: this.$t('realTimeData.importSus'),
                  type: 'success'
                });
              }
            })
          })
          .catch(() => {
            this.$message({
              showClose: true,
              type: "info",
              message: this.$t('orderQuery.cue2')
            });
          });
        } else {
          return false;
        }
      })
    },
    // 外部数据导入
    confirmOutImport() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$confirm(this.$t('approvalDetail.cue1'), {
            confirmButtonText: this.$t('btn.confirm'),
            cancelButtonText: this.$t('btn.cancel'),
            type: "warning",
            center: true
          })
          .then(() => {
            let obj = new FormData()
            obj.append('file', this.form.file)
            outsideImport(obj, this.form.innerType, this.form.channel, this.form.description).then(res => {
              if (res.status === 200) {
                this.dialogFormVisible2 = false;
                this.getList();
                this.$message({
                  showClose: true,
                  message: this.$t('realTimeData.importSus'),
                  type: 'success'
                });
              }
            })
          })
          .catch(() => {
            this.$message({
              showClose: true,
              type: "info",
              message: this.$t('orderQuery.cue2')
            });
          });
        } else {
          return false;
        }
      })
    },
    // 日期初始化
    initDate() {
      this.listQuery.startDate = this.GetDateStr(-7);
      this.listQuery.endDate = this.GetDateStr(-1);
    },
    GetDateStr(AddDayCount) {
      const dd = new Date();
      dd.setDate(dd.getDate() + AddDayCount);// 获取AddDayCount天后的日期
      const y = dd.getFullYear();
      const m = (dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1); // 获取当前月份的日期，不足10补0
      const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate(); // 获取当前几号，不足10补0
      return y + '-' + m + '-' + d;
    },
    // 选中的数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 指定代理人
    assignedTo() {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          showClose: true,
          message: this.$t('approvalDispatch.msg1'),
          type: 'warning'
        });
      } else {
        this.dialogFormVisible = true
      }
    },
    // 指定处理人确认按钮
    confirmFn() {
      if (this.serviceId !== '') {
        const channel = this.listQuery.channel
        const ids = []
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
        const designatedId = this.serviceId
        const designatedName = this.getHandlerName(designatedId)
        const params = {
          channel,
          ids,
          designatedId,
          designatedName
        }
        assignHandler(params).then(res => {
          if (res.status === 200) {
            this.$message({
              showClose: true,
              message: this.$t('approvalDispatch.opersuccess'),
              type: 'success'
            });
            this.dialogFormVisible = false
            this.serviceId = ''
            this.getList()
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'warning'
            });
          }
        })
      } else {
        this.$message({
          showClose: true,
          message: this.$t('rule.pleAssignTo'),
          type: 'warning'
        });
      }
    },
    handlebeforeClose() {
      this.dialogFormVisible = false
      this.serviceId = ''
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>

<style scoped lang='scss'>
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before{
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px  0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div:nth-child(2) {
      width: 150px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px  0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
       width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.handler {
  width: 90%;
  display: flex;
  justify-content: space-between;
  align-items: center;
    span {
      display: inline-block;
      width: 80px;
      text-align: center;
      font-size: 14px;
      font-weight: bold;
    }
    div:nth-child(2) {
      flex: 1;
    }
}
.menu-list {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.bg {
  display: inline-block;
  border-radius: 5px;
  border: 2px solid #fff;
  width: 25px;
  height: 25px;
  cursor: pointer;
}
.color1 {
  background: #ec7070;
}
.color2 {
  background: #73d466;
}
.type-marker {
  display: flex;
  align-items: center;
  margin-right: 20px;
}
.hiddenInput{
  display: none;
}
</style>